package org.ainlolcat.ainscience.entity;

import org.ainlolcat.ainscience.transformer.Transformer;
import org.ainlolcat.ainscience.templates.Template;
import org.ainlolcat.ainscience.tools;
import org.jdom.Element;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by IntelliJ IDEA.
 * User: ain
 * Date: 11/10/11
 * Time: 8:22 AM
 * To change this template use File | Settings | File Templates.
 */
public class EntityTransformer {

    /**
     * pass entity to some class which handle changes like baseline and other
     * basicly it SimpleEntity related staff but wil it be for now because it dont use any forbidden API
     * @param entity
     * @return
     * @throws ClassNotFoundException
     * @throws IllegalAccessException
     * @throws InstantiationException
     */
    public Entity applyChangesToEntity(Entity entity) throws ClassNotFoundException, IllegalAccessException, InstantiationException {
        Template template = entity.getTemplate();
        String type = entity.getType();
        Element parse_params = template.getEntityParseParams(type);
        List<Element> changes = parse_params.getChild("columnChanges")==null?
                                        new ArrayList<Element>():
                                        parse_params.getChild("columnChanges").getChildren("change");
        for (Element el:changes){
            try{
                Class changeHandler = Class.forName(el.getAttributeValue("class"));
                Element params = el.getChild("parameters");
                Transformer handler = (Transformer) changeHandler.newInstance();
                if (params!=null){
                    handler.handle(entity, tools.parseInteger(el.getAttributeValue("column")), params);
                }else {
                    handler.handle(entity, tools.parseInteger(el.getAttributeValue("column")));
                }
            } catch(Exception e){
                e.printStackTrace();
            }
        }
        return entity;
    }
}
